package com.csrcb.tools;

import java.io.*;
import java.util.Map;

/**
 * @Classname ObjectReadWriteFileUtil
 * @Description 讲对象读写文件
 * @Date 2020/12/17 15:55
 * @Created by gangye
 */
public class ObjectReadWriteFileUtil {

    public void writeObject(String filePath,Map<String,Object> calcTimes) {
        FileOutputStream out;
        ObjectOutputStream objectOut = null;
        try {
            out = new FileOutputStream(filePath);
            objectOut = new ObjectOutputStream(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            objectOut.writeObject(calcTimes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String readObject(String filePath) {
        Map<String, Object> content = null;
        FileInputStream in = null;
        ObjectInputStream objectIn = null;
        try {
            in = new FileInputStream(filePath);
            objectIn = new ObjectInputStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            content = (Map<String, Object>) objectIn.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                objectIn.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for(String key : content.keySet()){
            System.out.println(key+":"+content.get(key));
        }
        return content.toString();
    }

//    public static void main(String[] args) {
//        //写入
//        Map<String,Object> calcTimes = new HashMap<>();
//        calcTimes.put("headErrorTimes",0);
//        calcTimes.put("emsSendTimes",0);
//        new ObjectReadWriteFileUtil().writeObject("testFile.txt",calcTimes);
//
//        //读取
//        String val = new ObjectReadWriteFileUtil().readObject("testFile.txt");
//        if (val == null || "".equals(val)){
//            System.out.println("111111111");
//        }else{
//            System.out.println(val);
//        }
//    }

}
